using System;
using System.Reflection;
using ZFramework.Runtime;

namespace ZGame
{
    public class ProcedureLoadAssembly : ProcedureBase
    {
        //程序集是否加载完毕
        private bool _loadAssemblyComplete;
        
        //元数据是否加载完毕
        private bool _loadMetadataAssemblyComplete;
        
        //热更主程序集
        private Assembly _mainLogicAssembly;

        private bool _isPlaying;

        public override void OnEnter(Fsm<IProcedureManager> procedureOwner)
        {
            base.OnEnter(procedureOwner);
            _isPlaying = false;
            _loadAssemblyComplete = false;
            _loadMetadataAssemblyComplete = false;
            
            if (AOTGameEntry.baseMgr.PlayMode == BaseMgr.EResourceMode.OfflinePlayMode)
            {
                //编辑器单机模式直接获取程序集
                _mainLogicAssembly = GetMainLogicAssembly();
                _loadAssemblyComplete = true;
                _loadMetadataAssemblyComplete = true;
            }
            else
            {
                Log.Error("暂时还没做这个模式，请切换到单机模式");
            }
        }

        public override void OnUpdate(Fsm<IProcedureManager> procedureOwner, float elapseSeconds, float realElapseSeconds)
        {
            base.OnUpdate(procedureOwner, elapseSeconds, realElapseSeconds);
            if (!_loadAssemblyComplete)
                return;
            
            if (!_loadMetadataAssemblyComplete)
                return;

            if (!_isPlaying)
            {
                _isPlaying = true;
                AllAsmLoadComplete();
            }
        }

        private void LoadAssembly(byte[] assemblyData)
        {
            //var asm = Assembly.Load(assemblyData);
        }

        //获取逻辑主程序集
        private Assembly GetMainLogicAssembly()
        {
            Assembly mainLogicAssembly = null;
            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                if(string.Compare("Hotfix.Game.dll", $"{assembly.GetName().Name}.dll", StringComparison.Ordinal) == 0)
                {
                    mainLogicAssembly = assembly;
                    break;
                }
            }

            return mainLogicAssembly;
        }

        private void AllAsmLoadComplete()
        {
            if (_mainLogicAssembly == null)
            {
                Log.Error("主程序集为空");
                return;
            }

            var gameApp = _mainLogicAssembly.GetType("ZGame.GameApp");
            if (gameApp == null)
            {
                Log.Error("找不到GameApp");
                return;
            }

            var beginMethod = gameApp.GetMethod("Init");
            if (beginMethod == null)
            {
                Log.Error("GameApp找不到Init入口函数");
                return;
            }

            beginMethod.Invoke(gameApp, null);
        }
    }
}